<template>
  <div>
    <van-index-bar
      :index-list="computedCityList"
    >
      <div v-for="data in cityList" :key="data.type">
        <van-index-anchor :index="data.type">
          <van-cell @click="handleChangePage(item)" :title="item.name" :key="index" v-for="(item, index) in data.list"></van-cell>
        </van-index-anchor>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import http from '../utils'
import { mapMutations } from 'vuex'

export default {
  data() {
    return {
      cityList: []
    }
  },
  mounted() {
    http({
      url: '/gateway?k=2323064',
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then(({ data }) => {
      console.log(data);
      this.handleCityData(data.data.cities)
    })
  },
  computed: {
    computedCityList() {
      return this.cityList.map(item => item.type)
    }
  },
  methods: {
    ...mapMutations(['changeCityData']),
    handleCityData(data) {
      // 数据处理为二维数组
      let letterArr = []
      for(let code = 65; code < 91; code++) {
        letterArr.push(String.fromCharCode(code))
      }
      let newCitys = []
      letterArr.forEach(letter => {
        const list = data.filter(item => item.pinyin.substring(0,1).toUpperCase() === letter)
        if(list.length) {
          newCitys.push({
            type: letter,
            list
          })
        }
      })
      this.cityList = newCitys
      console.log(letterArr, newCitys);
    },
    handleChangePage(data) {
      this.changeCityData(data)
      this.$router.back()
    }
  }
}
</script>